package com.sunny.ynhz.ui;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;

import com.sunny.ynhz.R;
import com.sunny.ynhz.adapter.GroupAdapter;
import com.sunny.ynhz.bean.DocBean;
import com.sunny.ynhz.ui.base.AppBaseTranslationTitleBarActivity;
import com.sunny.ynhz.utils.FileSizeExhangeUtils;
import com.sunny.ynhz.utils.ShowUtils;
import com.sunny.ynhz.utils.SortFileTimeD_X;
import com.sunny.ynhz.utils.ToastUtils;
import com.sunny.ynhz.widget.CustomExpandListview;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

;

public class SelectFileActivity extends AppBaseTranslationTitleBarActivity {
    Map<String,List<DocBean>> map=new HashMap<>();
    ArrayList<String> mListName=new ArrayList<>();
    ArrayList<DocBean> mlistDocBean=new ArrayList<>();
    List<String> tempFilePaths=new ArrayList<>();
    private CustomExpandListview customExpandListview;
    private boolean b;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            ShowUtils.closePopwindow();
            cursor.close();
            customExpandListview.setAdapter(new GroupAdapter(SelectFileActivity.this,mListName,map,customExpandListview));
            View view = LayoutInflater.from(SelectFileActivity.this).inflate(R.layout.list_title, null);
            customExpandListview.setHeaderView(view);
            customExpandListview.setGroupIndicator(null);
        }
    };
    private ArrayList<String> data;
    private Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_file);
        Intent intent = getIntent();
        data = intent.getStringArrayListExtra("data");
        setTitle("选择文件");
        setRightTextView("确定","#ffffff");
        setRightTextViewSize(18);
        customExpandListview = findViewById(R.id.custom_view);
        ShowUtils.inItPopwin(this,"加载中");
        new Thread(new Runnable() {
            @Override
            public void run() {
                getQQFile();
                queryFiles();
            }
        }).start();
        customExpandListview.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
                String fileType= mListName.get(i);
                if(new File(map.get(fileType).get(i1).getPath()).length()>1024*1024*10){
                    ToastUtils.SingleToastUtil(SelectFileActivity.this,"单个文件不能超过10M");
                    return false;
                }
                DocBean docBean = map.get(mListName.get(i)).get(i1);
                if(getmListString().size()>=9&&!docBean.isCheck()){
                    ToastUtils.SingleToastUtil(SelectFileActivity.this,"选择的文件数量不能大于9个");
                }
                else {
                    ImageView ic_check=view.findViewById(R.id.ic_check);
                    if(docBean.isCheck()){
                        docBean.setCheck(false);
                        ic_check.setImageResource(R.mipmap.ic_unchecked);
                    }
                    else {
                        docBean.setCheck(true);
                        ic_check.setImageResource(R.mipmap.ic_checked);
                    }
                }

                return false;
            }
        });
    }
    private void queryFiles(){
        String[] projection = new String[] { MediaStore.Files.FileColumns._ID,
                MediaStore.Files.FileColumns.DATA,
                MediaStore.Files.FileColumns.SIZE,
                MediaStore.Files.FileColumns.DATE_MODIFIED
        };
        cursor = getContentResolver().query(
                MediaStore.Files.getContentUri("external"),
        projection,
                MediaStore.Files.FileColumns.MIME_TYPE + "=? or "+  MediaStore.Files.FileColumns.MIME_TYPE + "=? or "+
                MediaStore.Files.FileColumns.MIME_TYPE + "=? or " +  MediaStore.Files.FileColumns.MIME_TYPE + "=? or "+ MediaStore.Files.FileColumns.MIME_TYPE + "=?",
        new String[]{"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel","application/pdf"},
        MediaStore.Files.FileColumns.DATE_MODIFIED+" DESC");

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int idindex = cursor.getColumnIndex(MediaStore.Files.FileColumns._ID);
                int dataindex = cursor
                        .getColumnIndex(MediaStore.Files.FileColumns.DATA);
                int sizeindex = cursor
                        .getColumnIndex(MediaStore.Files.FileColumns.SIZE);
                int dataTime= cursor.getColumnIndex(MediaStore.Files.FileColumns.DATE_MODIFIED);
                do {
                    DocBean docBean=new DocBean();
                    String id = cursor.getString(idindex);
                    String path = cursor.getString(dataindex);
                    String size = cursor.getString(sizeindex);
                    docBean.setId(id);
                    docBean.setPath(path);
                    long i = Long.parseLong(size);
                    docBean.setSize(FileSizeExhangeUtils.getPrintSize(i));
                    int dot=path.lastIndexOf("/");
                    String name=path.substring(dot+1);
                    docBean.setName(name);
                    if(data.contains(path)){
                        docBean.setCheck(true);
                    }
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    docBean.setTimeDate(simpleDateFormat.format(new Date(cursor.getLong(dataTime)*1000)));
                    docBean.setTimestamp(cursor.getLong(dataTime)*1000);
                    getNeedFile(docBean, name);
                    b = cursor.moveToNext();
                    if(!b){
                        List<DocBean> excel = map.get("excel");
                        if(excel!=null){
                            SortFileTimeD_X.getSortD_X(excel);
                        }
                        List<DocBean> word=map.get("doc");
                        if(word!=null){
                            SortFileTimeD_X.getSortD_X(word);
                        }
                        List<DocBean> pdf = map.get("pdf");
                        if(pdf!=null){
                            SortFileTimeD_X.getSortD_X(pdf);
                        }
                        handler.sendEmptyMessage(0);
                    }
                } while (b);
            }
        }
    }

    private void getNeedFile(DocBean docBean, String name) {
        if(!tempFilePaths.contains(docBean.getPath())){
            if(name.contains(".xls")){
                if(map.get("excel")==null){
                    ArrayList<DocBean> mlist=new ArrayList<>();
                    mlist.add(docBean);
                    map.put("excel",mlist);
                    mListName.add("excel");
                }
                else {
                    List<DocBean> mlistTxt = map.get("excel");
                    mlistTxt.add(docBean);
                    map.put("excel",mlistTxt);
                }
            }
            else if(name.contains(".doc")){
                if(map.get("doc")==null){
                    ArrayList<DocBean> mlist=new ArrayList<>();
                    mlist.add(docBean);
                    map.put("doc",mlist);
                    mListName.add("doc");
                }
                else {
                    List<DocBean> mlistTxt = map.get("doc");
                    mlistTxt.add(docBean);
                    map.put("doc",mlistTxt);
                }
            }
            else if(name.contains(".pdf")){
                if(map.get("pdf")==null){
                    ArrayList<DocBean> mlist=new ArrayList<>();
                    mlist.add(docBean);
                    map.put("pdf",mlist);
                    mListName.add("pdf");
                }
                else {
                    List<DocBean> mlistTxt = map.get("pdf");
                    mlistTxt.add(docBean);
                    map.put("pdf",mlistTxt);
                }
            }
            mlistDocBean.add(docBean);
        }
    }

    @Override
    public void clickRightTextView() {
        super.clickRightTextView();
        ArrayList<String> strings = getmListString();
        Intent intent=new Intent();
        intent.putStringArrayListExtra("paths",strings);
        setResult(205,intent);
        finish();
    }
    public ArrayList<String> getmListString(){
        ArrayList<String> mList=new ArrayList<>();
        for (int i=0;i<mlistDocBean.size();i++){
            DocBean docBean = mlistDocBean.get(i);
            if(docBean.isCheck()){
                mList.add(docBean.getPath());
            }
        }
        return mList;
    }

    /**
     * 对qq的文件夹进行遍历
     */
    public void getQQFile(){
        traverseFolder("/storage/emulated/0/tencent/QQfile_recv");
    }
    public void traverseFolder(String path) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length!= 0) {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        traverseFolder(file2.getAbsolutePath());
                    } else {
                        String absolutePath = file2.getAbsolutePath();
                        if(absolutePath.endsWith(".doc")||absolutePath.endsWith(".docx")||absolutePath.endsWith(".xls")||absolutePath.endsWith(".xlsx")||absolutePath.endsWith(".pdf")){
                            int dot=absolutePath.lastIndexOf("/");
                            String name=absolutePath.substring(dot+1);
                            DocBean docBean=new DocBean();
                            if(data.contains(absolutePath)){
                              docBean.setCheck(true);
                            }
                            docBean.setName(name);
                            docBean.setSize(FileSizeExhangeUtils.getPrintSize(file2.length()));
                            docBean.setPath(absolutePath);
                            docBean.setTimeDate(simpleDateFormat.format(new Date(file2.lastModified())));
                            docBean.setTimestamp(file2.lastModified());
                            getNeedFile(docBean,name);
                            tempFilePaths.add(absolutePath);
                        }
                    }

                }
            }
        }
    }
}